package com.chen.service.impl;

import com.chen.pojo.ImageVO;
import com.chen.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;

@Service
@PropertySource(value = "classpath:/properties/image.properties", encoding = "UTF-8")
public class FileServiceImpl implements FileService {

    @Value("${image.fileDir}")
    private String fileDir;  //本地图片文件路径

    @Value("${image.urlPath}")
    private String urlPath;  //域名地址

    private static Set<String> imgTypeSet = new HashSet<>();

    static {
        //利用配置文件动态将图片类型获取.
        imgTypeSet.add(".jpg");
        imgTypeSet.add(".png");
        imgTypeSet.add(".gif");
    }

    /**
     * 业务逻辑:实现文件上传
     * 步骤:
     * 1.校验图片的类型  jpg|png|gif.......
     * 2.校验文件是否为恶意程序...
     * 3.采用分目录的结构进行存储
     * 4.避免文件重名  UUID
     */
    @Override
    @Transactional
    public ImageVO upload(MultipartFile uploadFile) {
        //一. 校验图片类型  1.利用集合校验   2.正则表达式
        //1.1 获取文件名称  1.jpg  1.JPG
        String fileName = uploadFile.getOriginalFilename();
        //1.2 获取下标 获取文件后缀类型
        String imgFileType = fileName.substring(fileName.toLowerCase().lastIndexOf("."));
        //1.3 判断是否为图片类型
        if (!imgTypeSet.contains(imgFileType)) return ImageVO.fail();

        //二.如果是图片  高度/宽度
        //2.1将数据转化为图片对象

        try {
            BufferedImage bufferedImage = ImageIO.read(uploadFile.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if (width == 0 || height == 0) {
                return ImageVO.fail();
            }
            //三 实现分目录存储
            String fileDir = "D:/javaStudy/projects/katerina/src/main/resources/static/images";
            //3.1按照/yyyy/MM/dd/的方式进行目录划分
            String dateDirPath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());

            String fileDirPath = new StringBuffer(fileDir).append(dateDirPath).toString();
            File dirFile = new File(fileDirPath);
            //3.2 创建目录
            if (!dirFile.exists()) dirFile.mkdirs();
            //四. 实现文件上传
            //4.1 准备文件名称 UUID  522f88bb-33b2-11eb-93fb-00d861eaf238
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //4.2 动态生成文件名称  uuid.jpg
            String uuidName = uuid + imgFileType;
            //4.3 实现文件上传
            File realFile = new File(fileDirPath + uuidName);
            uploadFile.transferTo(realFile);
            String url = urlPath + dateDirPath + uuidName;
            return ImageVO.success(url, width, height);
            // http://image.ktln.com/2020/12/194ff923914b0a4c7f83c3c570f949056a.jpg

        } catch (IOException e) {
            e.printStackTrace();
            return ImageVO.fail();
        }
    }
}
